<template>
    <Dialog :app-dialog="appDialog" @close="close">
        <el-scrollbar max-height="600px" class="create-link-quick">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
                <!-- 分组 -->
                <el-form-item label="分组">
                    <el-cascader
                        ref="cascaderRef"
                        v-model="form.group_id"
                        style="width: 100%"
                        :options="groupData"
                        :props="defaultProps"
                        placeholder="请选择分组"
                        @change="orgChange" />
                </el-form-item>
                <!-- 标题 -->
                <el-form-item label="链接标题" prop="title">
                    <el-input
                        v-model="form.title"
                        maxlength="20"
                        show-word-limit
                        :placeholder="`请输入链接标题`"
                        @input="btKeyUp($event, '1')">
                    </el-input>
                </el-form-item>
                <!-- 链接地址 -->
                <el-form-item label="链接地址" prop="link">
                    <div class="link-url">
                        <el-input v-model="form.link" type="text" placeholder="请输入链接地址"></el-input>
                        <el-tooltip placement="top">
                            <template #content>
                                <span v-html="tagTips.linkUrlTips"></span>
                            </template>
                            <el-icon><InfoFilled /></el-icon>
                        </el-tooltip>
                    </div>
                </el-form-item>
                <!-- 连接描述 -->
                <el-form-item label="链接描述" prop="linkDesc">
                    <el-input
                        v-model="form.linkDesc"
                        type="textarea"
                        :rows="3"
                        maxlength="30"
                        show-word-limit
                        placeholder="请输入链接描述"></el-input>
                </el-form-item>
                <!-- 上传文件 -->
                <ZWUpload ref="emptyData" :up-info="picInfo" class="upload-img" @submit="getFileList" />
                <el-form-item>
                    <template #label>
                        <div class="label_text">
                            <span>素材标签</span>
                            <el-tooltip :content="tagTips.materialTagTips" placement="top">
                                <img src="@/assets/image/material/question.png" alt="" />
                            </el-tooltip>
                        </div>
                    </template>
                    <selectTags ref="tagIdsRef" v-model="form.tag_ids" />
                </el-form-item>
                <el-form-item label="是否强制授权">
                    <el-radio-group v-model="form.is_force_grant" @change="changeAuth">
                        <el-radio :label="1">否</el-radio>
                        <el-radio :label="2">是(授权公众号头像昵称)</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item>
                    <template #label>
                        <div class="label_text">
                            <span>浏览打标</span>
                            <el-tooltip :content="tagTips.browseCustTips" placement="top">
                                <img src="@/assets/image/material/question.png" alt="" />
                            </el-tooltip>
                        </div>
                    </template>
                    <selectTags ref="viewtagIdsRef" v-model="form.view_tag_ids" :type="2" />
                </el-form-item>
                <el-form-item>
                    <template #label>
                        <div class="label_text">
                            <span>分享打标</span>
                            <el-tooltip :content="tagTips.shareCustTips" placement="top">
                                <img src="@/assets/image/material/question.png" alt="" />
                            </el-tooltip>
                        </div>
                    </template>
                    <selectTags ref="shareTagIdsRef" v-model="form.share_tag_ids" :type="2" />
                </el-form-item>

                <el-form-item label="">
                    <div class="agree_ment">
                        <!-- 暂时隐藏掉,协议要先不上需要法务确认 -->

                        <!-- <el-checkbox v-model="form.check" @change="confirmSure"></el-checkbox>
            <span class="ml2">勾选代表同意</span>
            <el-link class="form-link" type="primary" :underline="false">《***用户协议》</el-link> -->
                    </div>
                </el-form-item>
            </el-form>
        </el-scrollbar>
    </Dialog>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch, onUnmounted } from 'vue';
import Dialog from '@/components/Dialog.vue';
import ZWUpload from './ZWUpload.vue';
import selectTags from '../../../components/selectTags.vue';
import { quickLink, updateLink, linkInfos, getGroupList } from '@/api/concreation';
import { ElForm, ElMessage } from 'element-plus';
import { getSetionId } from '@/utils/utils';
import bus from '@/utils/bus';
import { useStore } from '@/store';
import { endLoading, startLoading } from '@/utils/request';

const formRef = ref<InstanceType<typeof ElForm>>();
const cascaderRef: any = ref(null); // 选择分组ref
const emit = defineEmits(['submit']);
const props = defineProps(['groupId', 'type']);

const store = useStore();
const uploadTitle = ref('上传文件');
const uploadVisib = ref(false);
const isEdit = ref(false);
const emptyData = ref(); // 清空回显数据
const componentKey = ref(0);
const tagIdsRef = ref(null);
const viewtagIdsRef = ref(null);
const shareTagIdsRef = ref(null);
const tagTips = {
    materialTagTips: '该素材会被打上此素材标签，在列表上会展示',
    browseCustTips: '浏览该素材的客户将被打上此客户标签',
    shareCustTips: '点击该素材的分享按钮并生成分享链接的客户将被打上此客户标签',
    linkUrlTips:
        '因外部链接（域名非keyid.cn的链接）的限制问题，链接地址<br/>为外部链接时不支持统计浏览器时长、客户分享相关数据。'
};
//上传弹框
const uploadInfo = computed(() => {
    return store.getters['content/upload'];
});

// 分组列表
const groupData = ref([]);

/**
 * @description: 获取分组数据
 * @return {*}
 */
const getGroupListFunc = async () => {
    const res = await getGroupList({ type: props.type });
    groupData.value = res.data;
};
//标签
const tags = computed(() => {
    return store.getters['content/tagsInfo'].tags;
});
const defaultProps = {
    checkStrictly: true,
    emitPath: false,
    label: 'name',
    value: 'id'
};
const form = reactive({
    tag_ids: [],
    view_tag_ids: [],
    group_id: 0, //分组
    type: 0,
    tags: [], //标签
    check: true, //用户协议
    title: '', //标题
    link: '', //链接地址
    cover: '', //连接封面
    linkDesc: '', // 连接描述
    id: '', //内容id
    content: '', //链接内容
    is_force_grant: 1,
    share_tag_ids: []
});
// 图片上传
const picInfo = reactive({
    type: 1,
    label: '封面',
    prop: 'cover',
    files: form.cover,
    multiple: true,
    limitSize: 2,
    limitNum: 1,
    acceptFile: '.jpg,.jpeg,.png,.bmp,.webp'
});

const close = () => {
    form.group_id = props.groupId;
};

//校验链接
const confirmUrl = (rule: any, value: any, callback: any) => {
    if (value == '') callback(new Error('链接不能为空'));
    const isHttp = /(https):\/\/([\w.]+\/?)\S*/.test(value);
    if (isHttp) {
        callback();
    } else {
        callback(new Error('请输入以https开头的链接'));
    }
};
//禁止输入特殊字符
const btKeyUp = (e: any, type: any) => {
    switch (type) {
        case '1': //标题
            form.title = e
                .replace(
                    /[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
                    ''
                )
                .replace(/\s/g, '');
            break;
        case '3': //描述
            form.linkDesc = e
                .replace(
                    /[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
                    ''
                )
                .replace(/\s/g, '');
            break;
    }
};
const rules = reactive({
    title: [
        {
            required: true,
            message: '链接标题不能为空',
            trigger: 'blur'
        }
    ],
    link: [
        {
            required: true,
            message: '链接地址不能为空',
            trigger: 'blur'
        },
        {
            validator: confirmUrl,
            trigger: 'blur'
        }
    ],
    linkDesc: [
        {
            required: true,
            message: '链接描述不能为空',
            trigger: 'blur'
        }
    ],
    cover: [
        {
            required: true,
            message: '封面不能为空',
            trigger: 'change'
        }
    ]
});

// 获取上传成功的文件
const getFileList = (data: any) => {
    try {
        const arr: any[] = getSetionId('code', data);
        form.cover = arr[0];
    } catch (error) {
    } finally {
        endLoading();
    }
};
// 取消
const cancelHandel = () => {
    appDialog.visible = false;
    uploadVisib.value = false;
    isEdit.value = false;
    delUpform();
    close();
    formRef.value.resetFields();
};
//确定
const submitHandel = () => {
    formRef.value.validate(async (valid: any) => {
        if (valid) {
            operate();
        }
    });
};
const operate = async () => {
    const groupId = form.group_id;
    const params = {
        title: form.title,
        group_id: form.group_id,
        file_type: form.type,
        code: '',
        tag_ids: getSetionId('id', form.tag_ids),
        view_tag_ids: getSetionId('id', form.view_tag_ids),
        media_content_id: form.id,
        link: form.link,
        desc: form.linkDesc,
        cover_code: form.cover,
        content: form.content,
        is_force_grant: form.is_force_grant,
        share_tag_ids: getSetionId('id', form.share_tag_ids)
    };
    startLoading();
    try {
        // 修改
        if (isEdit.value) {
            await updateLink({ ...params, type: 7 });
            isEdit.value = false;
            ElMessage.success('修改链接成功');
            emit('submit', { refresh: true, id: groupId });
            cancelHandel();
            forceRerender();
        } else {
            await quickLink(params);
            ElMessage.success('快速创建链接成功！');
            emit('submit', { refresh: true, id: groupId });
            cancelHandel();
            bus.emit('delUpform');
            forceRerender();
        }
    } catch (e) {
        endLoading();
    }
};
const forceRerender = () => {
    componentKey.value += 1;
};
const appDialog = reactive({
    visible: uploadVisib,
    title: uploadTitle,
    width: '670px',
    cancel: cancelHandel,
    submit: submitHandel,
    isDisable: false,
    cancelText: '取消',
    submitText: '保存'
});
const confirmSure = (val: boolean) => {
    appDialog.isDisable = !val;
};

//获取编辑内容
const editItem = (data: any) => {
    isEdit.value = true;
    // 6创建链接编辑 7快速创建编辑
    const params = {
        media_content_id: data.media_content_id
    };
    linkInfos(params).then((data: any) => {
        // tag_ids 素材标签
        // view_tag_ids 浏览客户标签
        // share_tag_ids 分享客户标签
        form.tag_ids = data.tag_info;
        form.view_tag_ids = data.view_tag_info;
        form.share_tag_ids = data.share_tag_info;
        form.title = data.title;
        form.group_id = data.group_id;
        form.tags = data.tag_info;
        form.type = data.is_radar;
        form.id = data.id;
        form.cover = data.link_info.cover_image_url;
        form.link = data.link_info.ref_url;
        form.linkDesc = data.desc;
        form.content = data.link_info.content;
        form.is_force_grant = data.is_force_grant;
        emptyData.value.echo(data.link_info);
        // bus.emit('echo', data.link_info)
        setTimeout(() => {
            tagIdsRef.value?.init();
            viewtagIdsRef.value?.init();
            shareTagIdsRef.value?.init();
        }, 0);
    });
};
// 清空上传表单数据
const delUpform = () => {
    Object.keys(form).map(key => {
        if (key != 'group_id') {
            delete form[key];
        }
    });
    // bus.emit('empty')
    emptyData.value.empty();
};
bus.on('delUpform', delUpform);
bus.on('editItem', editItem);
watch(uploadInfo, uploadInfo => {
    uploadTitle.value = uploadInfo.title;
    uploadVisib.value = uploadInfo.uploadVisib;
    if (uploadVisib.value) {
        getGroupListFunc();
    }

    form.is_force_grant = 1;
});
watch(
    () => props.groupId,
    val => {
        form.group_id = val ? val : 0;
    },
    { immediate: true, deep: true }
);
watch(tags, data => {
    form.tags = data;
});
watch(
    () => form.cover,
    () => {
        formRef.value.validateField('cover');
    }
);

// 选择完地区后立即关闭
const orgChange = () => {
    cascaderRef.value.togglePopperVisible();
};
onUnmounted(() => {
    bus.off('editItem', editItem);
});
defineExpose({
    form
});
</script>
<style lang="scss" scoped>
.upload-img {
    margin-bottom: 4px;
}

.create-link-quick {
    padding-top: 14px;
    padding-right: 20px;
}

.tags {
    margin-top: 15px;
}

.radio_list {
    &_item {
        &_icon {
            width: 14px;
            height: 14px;
            margin: -3px 0 0 6px;

            img {
                margin-top: 2px;
                width: 100%;
                height: 100%;
                vertical-align: top;
            }
        }
    }

    :deep .el-radio__label {
        display: flex;
        align-items: center;
    }
}

.ml2 {
    margin-left: 2px;
}

.mr10 {
    margin-right: 10px;
}

.agree_ment {
    display: flex;
    align-items: center;
}

:deep .el-scrollbar {
    height: 50%;
}

:deep(.el-form-item) {
    .label_text {
        display: flex;
        align-items: center;
        gap: 6px;

        img {
            width: 14px;
            height: 14px;
        }
    }
}

:deep(.link-url) {
    display: flex;
    align-items: center;
    gap: 6px;

    .el-icon {
        font-size: 20px;
        color: #f96b02;
    }
}
</style>
